package com.zenitera.bigdata.state;

import com.zenitera.bigdata.bean.WaterSensor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * ValueState<T>
 *
 */
public class Flink02_State_Key_ValueState {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        env
                .socketTextStream("localhost", 6666)
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(
                            String.valueOf(data[0]),
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private ValueState<Integer> lastVcState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastVcState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastVcState", Integer.class));
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {

                        Integer lastVc = lastVcState.value();
                        System.out.println(lastVc);

                        if (lastVc != null) {
                            System.out.println(lastVc + "  " + value.getVc());
                            if (value.getVc() > 10 && lastVc > 10) {
                                out.collect(ctx.getCurrentKey() + " to High! ++10 ");
                            }
                        }

                        lastVcState.update(value.getVc());

                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/*
D:\netcat-win32-1.12>nc64.exe -lp 6666
s1,1,3
s1,1,9
s1,1,10
s1,1,12
s1,1,14
s1,1,15
s1,1,2
s1,1,100
s1,1,3
s1,1,100
s1,1,100
-----------------------------------------
null
3
3  9
9
9  10
10
10  12
12
12  14
s1 to High! ++10
14
14  15
s1 to High! ++10
15
15  2
2
2  100
100
100  3
3
3  100
100
100  100
s1 to High! ++10
 */